<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const flatArray = [{
                id: 1,
                parentId: null,
                name: 'root1'
            },
            {
                id: 2,
                parentId: 1,
                name: 'child1'
            }, {
                id: 3,
                parentId: 1,
                name: 'child2'
            }, {
                id: 4,
                parentId: 2,
                name: "grandchild1" }, 
                {id:5,
                parentId:3,
                name: "grandchild2"
            },
        ]

        function toTree(arr)
        {
            let map = new Map();
            let result = [];
            arr.forEach(item=>{
                map.set(item.id,{...item,children:[]});
            })

            arr.forEach(item=>{
                let node = map.get(item.id);
                if(node.parentId == null)
                {
                    result.push(node);
                }
                else
                {
                    let parentNode = map.get(item.parentId);
                    parentNode.children.push(node);
                }
            })

            return result;
        }
        console.log(JSON.stringify(toTree(flatArray)));
    </script>
</body>

</html>